package com.my.fss.listener;


/**
 *  主监听器
 *  监听web容器的，初始化，添加，移除等操作
 *
 * @author liuhx   2020-02-29
 */

//import com.my.fss.common.util.Configure;
import lombok.SneakyThrows;

import javax.servlet.*;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServlet;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

        import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
        import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.context.WebApplicationContext;

@WebListener
public class ServletListener extends HttpServlet implements ServletContextListener, ServletContextAttributeListener {

    @Autowired
    private Environment env;
    /** Servlet容器 */
    private ServletContext context = null;
    /** Spring注入对象 */
    private WebApplicationContext springContext;
    /** 日志 */
    private static Log logger = LogFactory.getLog(ServletListener.class);


    @SneakyThrows
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        try {

            logger.info("监听初始化web容器");

        } catch (Exception e) {
            logger.error("初始化容器失败");
        }
    }

    @Override
    public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) {
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) {
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) {
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        while (drivers.hasMoreElements()) {
            Driver driver = drivers.nextElement();
            try {
                DriverManager.deregisterDriver(driver);
                logger.info("驱动被注销");
            } catch (SQLException e) {
                logger.info(("注销驱动异常"), e);
                logger.info("销毁容器");
            }
        }

    }
}
